﻿using System;
using System.Collections.Generic;

using System.Text;

namespace Plain.Utilities{
    public static class CollectionExtensions {
        /// <summary>
        /// Copies the content of the list to an array and returns it
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static T[] ToArray<T>(this IList<T> list) {
            T[] array = new T[list.Count];
            list.CopyTo(array,0);
            return array;
        }
        
        public static string Join(this IList<string> list, string delimiter){
        	return String.Join(delimiter, list.ToArray());
        }
        
        public static string Join<T>(this IList<T> list, string delimiter){
        	IList<string> s = new List<string>();
        	foreach(T o in list){
        		s.Add(o.ToString());
        	}
        	return s.Join(delimiter);
        }
        /// <summary>
        /// Returns a multidimentional array
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static T[][] ToArray<T>(this IDictionary<T, T> dic) {
            T[][] array = new T[dic.Count][];
            int c = 0;
            foreach(KeyValuePair<T,T> pair in dic){
                array[c++] = new T[2] { pair.Key, pair.Value };
            }
            return array;
        }
        
        public static void Do<T>(this IEnumerable<T> list,Action<T> action){
        	foreach(T t in list){
        		action.Invoke(t);
        	}
        }
        public static IEnumerable<TResult> Do<T,TResult>(this IEnumerable<T> list,Func<T, TResult> func){
        	IList<TResult> results = new List<TResult>();
        	foreach(T t in list){
        		results.Add(func.Invoke(t));
        	}
        	return results;
        }
    }
}
